// 商品数据
const products = [
    {
        id: 1,
        name: "无线蓝牙耳机",
        description: "高品质音质，舒适佩戴，长续航时间",
        price: 299,
        category: "electronics",
        image: "https://picsum.photos/400/300?random=1",
        rating: 4.5,
        stock: 15
    },
    {
        id: 2,
        name: "时尚运动鞋",
        description: "轻便舒适，适合各种运动场合",
        price: 189,
        category: "clothing",
        image: "https://picsum.photos/400/300?random=2",
        rating: 4.2,
        stock: 8
    },
    {
        id: 3,
        name: "JavaScript高级程序设计",
        description: "前端开发必备经典书籍",
        price: 89,
        category: "books",
        image: "https://picsum.photos/400/300?random=3",
        rating: 4.8,
        stock: 20
    },
    {
        id: 4,
        name: "智能手表",
        description: "健康监测，消息提醒，运动记录",
        price: 599,
        category: "electronics",
        image: "https://picsum.photos/400/300?random=4",
        rating: 4.3,
        stock: 5
    },
    {
        id: 5,
        name: "纯棉T恤",
        description: "舒适透气，多种颜色可选",
        price: 59,
        category: "clothing",
        image: "https://picsum.photos/400/300?random=5",
        rating: 4.0,
        stock: 25
    },
    {
        id: 6,
        name: "咖啡机",
        description: "一键制作美味咖啡，家用办公首选",
        price: 399,
        category: "home",
        image: "https://picsum.photos/400/300?random=6",
        rating: 4.6,
        stock: 3
    },
    {
        id: 7,
        name: "React实战指南",
        description: "深入理解React框架和最佳实践",
        price: 79,
        category: "books",
        image: "https://picsum.photos/400/300?random=7",
        rating: 4.7,
        stock: 12
    },
    {
        id: 8,
        name: "台灯",
        description: "护眼设计，多档调光，节能环保",
        price: 129,
        category: "home",
        image: "https://picsum.photos/400/300?random=8",
        rating: 4.1,
        stock: 18
    }
];

// 购物车数据
let cart = [];
let cartTotal = 0;

// DOM元素
const productsGrid = document.getElementById('productsGrid');
const cartSidebar = document.getElementById('cartSidebar');
const cartItems = document.getElementById('cartItems');
const cartCount = document.getElementById('cartCount');
const cartTotalElement = document.getElementById('cartTotal');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const categoryFilter = document.getElementById('categoryFilter');
const priceFilter = document.getElementById('priceFilter');
const sortFilter = document.getElementById('sortFilter');
const closeCart = document.getElementById('closeCart');
const checkoutBtn = document.getElementById('checkoutBtn');
const cartIcon = document.querySelector('.cart-icon');
const authModal = document.getElementById('authModal');
const tabButtons = document.querySelectorAll('.tab-btn');
const authForms = document.querySelectorAll('.auth-form');

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    renderProducts(products);
    setupEventListeners();
    loadCartFromStorage();
});

// 设置事件监听器
function setupEventListeners() {
    // 购物车相关
    cartIcon.addEventListener('click', toggleCart);
    closeCart.addEventListener('click', closeCartSidebar);
    checkoutBtn.addEventListener('click', handleCheckout);
    
    // 搜索和筛选
    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') handleSearch();
    });
    
    categoryFilter.addEventListener('change', applyFilters);
    priceFilter.addEventListener('change', applyFilters);
    sortFilter.addEventListener('change', applyFilters);
    
    // 认证模态框
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tab = this.getAttribute('data-tab');
            switchAuthTab(tab);
        });
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(e) {
        if (e.target === authModal) {
            authModal.classList.remove('active');
        }
    });
}

// 渲染商品列表
function renderProducts(productsToRender) {
    productsGrid.innerHTML = '';
    
    if (productsToRender.length === 0) {
        productsGrid.innerHTML = '<p class="no-products">没有找到符合条件的商品</p>';
        return;
    }
    
    productsToRender.forEach(product => {
        const productCard = createProductCard(product);
        productsGrid.appendChild(productCard);
    });
}

// 创建商品卡片
function createProductCard(product) {
    const card = document.createElement('div');
    card.className = 'product-card';
    card.innerHTML = `
        <img src="${product.image}" alt="${product.name}" class="product-image">
        <div class="product-info">
            <h3 class="product-title">${product.name}</h3>
            <p class="product-description">${product.description}</p>
            <div class="product-rating">${generateStarRating(product.rating)}</div>
            <div class="product-price">¥${product.price}</div>
            <button class="add-to-cart" data-id="${product.id}">
                ${product.stock > 0 ? '加入购物车' : '缺货'}
            </button>
        </div>
    `;
    
    // 添加点击事件
    const addToCartBtn = card.querySelector('.add-to-cart');
    if (product.stock > 0) {
        addToCartBtn.addEventListener('click', () => addToCart(product));
    } else {
        addToCartBtn.disabled = true;
    }
    
    return card;
}

// 生成星级评分
function generateStarRating(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 !== 0;
    let stars = '';
    
    for (let i = 0; i < fullStars; i++) {
        stars += '★';
    }
    
    if (hasHalfStar) {
        stars += '☆';
    }
    
    const emptyStars = 5 - Math.ceil(rating);
    for (let i = 0; i < emptyStars; i++) {
        stars += '☆';
    }
    
    return stars + ` ${rating}`;
}

// 添加到购物车
function addToCart(product) {
    const existingItem = cart.find(item => item.id === product.id);
    
    if (existingItem) {
        if (existingItem.quantity < product.stock) {
            existingItem.quantity++;
        } else {
            alert('库存不足！');
            return;
        }
    } else {
        cart.push({
            ...product,
            quantity: 1
        });
    }
    
    updateCart();
    showNotification(`${product.name} 已添加到购物车`);
}

// 更新购物车
function updateCart() {
    // 更新购物车数量
    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
    cartCount.textContent = totalItems;
    
    // 更新购物车总价
    cartTotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    cartTotalElement.textContent = cartTotal.toFixed(2);
    
    // 更新购物车项目
    renderCartItems();
    
    // 保存到本地存储
    saveCartToStorage();
}

// 渲染购物车项目
function renderCartItems() {
    cartItems.innerHTML = '';
    
    if (cart.length === 0) {
        cartItems.innerHTML = '<p class="empty-cart">购物车为空</p>';
        return;
    }
    
    cart.forEach(item => {
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item';
        cartItem.innerHTML = `
            <img src="${item.image}" alt="${item.name}" class="cart-item-image">
            <div class="cart-item-details">
                <div class="cart-item-title">${item.name}</div>
                <div class="cart-item-price">¥${item.price}</div>
                <div class="cart-item-quantity">
                    <button class="quantity-btn minus" data-id="${item.id}">-</button>
                    <span>${item.quantity}</span>
                    <button class="quantity-btn plus" data-id="${item.id}">+</button>
                </div>
            </div>
            <button class="remove-item" data-id="${item.id}">×</button>
        `;
        
        cartItems.appendChild(cartItem);
    });
    
    // 添加数量按钮事件
    document.querySelectorAll('.quantity-btn.minus').forEach(btn => {
        btn.addEventListener('click', () => updateQuantity(btn.dataset.id, -1));
    });
    
    document.querySelectorAll('.quantity-btn.plus').forEach(btn => {
        btn.addEventListener('click', () => updateQuantity(btn.dataset.id, 1));
    });
    
    // 添加删除按钮事件
    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', () => removeFromCart(btn.dataset.id));
    });
}

// 更新商品数量
function updateQuantity(productId, change) {
    const item = cart.find(item => item.id === parseInt(productId));
    
    if (item) {
        const newQuantity = item.quantity + change;
        
        if (newQuantity <= 0) {
            removeFromCart(productId);
        } else if (newQuantity <= item.stock) {
            item.quantity = newQuantity;
            updateCart();
        } else {
            alert('库存不足！');
        }
    }
}

// 从购物车移除商品
function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== parseInt(productId));
    updateCart();
}

// 处理搜索
function handleSearch() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    applyFilters();
}

// 应用筛选和排序
function applyFilters() {
    let filteredProducts = [...products];
    const searchTerm = searchInput.value.toLowerCase().trim();
    const category = categoryFilter.value;
    const priceRange = priceFilter.value;
    const sortBy = sortFilter.value;
    
    // 搜索筛选
    if (searchTerm) {
        filteredProducts = filteredProducts.filter(product => 
            product.name.toLowerCase().includes(searchTerm) || 
            product.description.toLowerCase().includes(searchTerm)
        );
    }
    
    // 分类筛选
    if (category) {
        filteredProducts = filteredProducts.filter(product => product.category === category);
    }
    
    // 价格筛选
    if (priceRange) {
        if (priceRange === '200+') {
            filteredProducts = filteredProducts.filter(product => product.price >= 200);
        } else {
            const [min, max] = priceRange.split('-').map(Number);
            filteredProducts = filteredProducts.filter(product => 
                product.price >= min && product.price < max
            );
        }
    }
    
    // 排序
    switch (sortBy) {
        case 'price-low':
            filteredProducts.sort((a, b) => a.price - b.price);
            break;
        case 'price-high':
            filteredProducts.sort((a, b) => b.price - a.price);
            break;
        case 'rating':
            filteredProducts.sort((a, b) => b.rating - a.rating);
            break;
        default:
            // 默认排序保持原样
            break;
    }
    
    renderProducts(filteredProducts);
}

// 切换购物车侧边栏
function toggleCart() {
    cartSidebar.classList.toggle('active');
}

// 关闭购物车侧边栏
function closeCartSidebar() {
    cartSidebar.classList.remove('active');
}

// 处理结算
function handleCheckout() {
    if (cart.length === 0) {
        alert('购物车为空！');
        return;
    }
    
    // 在实际应用中，这里会跳转到支付页面
    alert(`订单提交成功！总计：¥${cartTotal.toFixed(2)}\n\n由于这是演示版本，支付功能需要后端支持。`);
    
    // 清空购物车
    cart = [];
    updateCart();
    closeCartSidebar();
}

// 切换认证标签页
function switchAuthTab(tab) {
    // 更新按钮状态
    tabButtons.forEach(button => {
        button.classList.toggle('active', button.dataset.tab === tab);
    });
    
    // 更新表单显示
    authForms.forEach(form => {
        form.classList.toggle('active', form.id === `${tab}Form`);
    });
}

// 显示通知
function showNotification(message) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #27ae60;
        color: white;
        padding: 1rem 2rem;
        border-radius: 5px;
        z-index: 1003;
        animation: slideIn 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 保存购物车到本地存储
function saveCartToStorage() {
    localStorage.setItem('shoppingCart', JSON.stringify(cart));
}

// 从本地存储加载购物车
function loadCartFromStorage() {
    const savedCart = localStorage.getItem('shoppingCart');
    if (savedCart) {
        cart = JSON.parse(savedCart);
        updateCart();
    }
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
    
    .empty-cart, .no-products {
        text-align: center;
        padding: 2rem;
        color: #666;
    }
`;
document.head.appendChild(style);